package base.aqs.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author chengzhang
 * 2021/9/9 11:28
 */
public class Semaphore02 {


    public static Semaphore semaphore = new Semaphore(0);

    public static void main(String[] args) throws InterruptedException {

        //创建一个线程个数固定为2的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        //将线程A添加到线程池
        executorService.submit(() -> {
            try {
                System.out.println(Thread.currentThread() + "A task over");
                semaphore.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        //将线程B添加到线程池
        executorService.submit(() -> {
            try {
                System.out.println(Thread.currentThread() + "A task over");
                semaphore.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        //(1)等待子线程执行任务A完毕，返回
        semaphore.acquire(2);


        //将线程C添加到线程池
        executorService.submit(() -> {
            try {
                System.out.println(Thread.currentThread() + "B task over");
                semaphore.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        //将线程D添加到线程池
        executorService.submit(() -> {
            try {
                System.out.println(Thread.currentThread() + "B task over");
                semaphore.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        //(1)等待子线程执行任务B完毕，返回
        semaphore.acquire(2);
        System.out.println("task is over!");
        //关闭线程池
        executorService.shutdown();
    }

}
